package com.appsky.drift.activity;

import java.util.ArrayList;

import com.alibaba.fastjson.JSONObject;
import com.appsky.drift.R;
import com.appsky.drift.adapter.ChatRoomContentAdapter;
import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.ChatMessage;
import com.appsky.drift.api.DLog;
import com.appsky.drift.api.JsonFactory;
import com.appsky.drift.api.Utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;

public class ChatTraditionActivity extends Activity {

	private ListView mainList;

	private AppSkyApp app;

	private ArrayList<ChatMessage> chatMessageList = new ArrayList<ChatMessage>();

	private JsonFactory jsonFactory = JsonFactory.getFactory();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_tradition_mod_layout);
		app = (AppSkyApp) getApplication();
		initView();
	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(
				Utils.ACTION_CHAT_MESSAGE_RECEIVER);
		registerReceiver(chatMessageReceiver, filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(chatMessageReceiver);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (chatMessageList != null) {
			chatMessageList.clear();
			chatMessageList = null;
		}
		super.onDestroy();
	}

	private void initView() {
		mainList = (ListView) findViewById(R.id.main_list);
		ChatRoomContentAdapter adapter = new ChatRoomContentAdapter(this,
				chatMessageList);
		mainList.setAdapter(adapter);
	}

	private BroadcastReceiver chatMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			DLog.i("Tradition收到聊天消息");
			JSONObject json = JSONObject.parseObject(intent
					.getStringExtra("json"));
			int id = json.getIntValue("id");
			boolean isMe;
			DLog.i("id:" + id);
			DLog.i("my id: " + app.myInfo.getUserId());
			if (id == app.myInfo.getUserId()) {
				isMe = true;
			} else {
				isMe = false;
			}
			ChatMessage chatMessage = new ChatMessage(json, isMe);
			chatMessageList.add(chatMessage);
			mainList.setSelection(chatMessageList.size() - 1);
		}
	};

}
